<?php

#	Fastfoo - CMS developer under CakePHP / http://fast-foo.com
#	Copyright (C) 2010  Antonio Irlandés García

#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.

#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.

#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.

class UsersController extends AppController{
	
	/*****************
	** Variables Generales
	*****************/
	public $name = 'Users';//nombre controlador
	public $uses = array('User', 'Group', 'Aco', 'Aro','Permission');//modelos empleados
	public $layout = 'admin';//disposición de diseño por defecto
	public $components = array('Passtrong');//componentes empleados

	/*****************
	** Variables Administracion
	*****************/
	public $search_form = true;//mostramos el buscador si o no
	public $cmp_search = 'User.username';//campo de la BD que emplearemos para la BD (filtrar en las busquedas)
	public $sub_menu = array("users" => "index", "groups" => "index");//Subsecciones en submenu
	public $action_menu = array("list_users" => "index","add_user"=>"view");//Acciones del menu accion
	public $lnregpp = array(20,40,60,80,100);//Numero de registros mostrados por pagina

	/*****************
	** Respuestas de controlador a una accion
	*****************/
	public $result_action;//Resultado de la operaciones
	public $msg_result;//Mensaje de la operacion

	/*****************
	** Otras variables
	*****************/
	private $_users_protected = array(array('id' => '4','username' => 'guest'));//Usuarios protegidos por el sistema, no pueden ser modificados


////////////////////////////////////////////////////////////////////////////
//////*METODOS PARA EL PUBLICO EN GENERAL*/////////////////////////////////
//////////////////////////////////////////////////////////////////////////

	/**
	 * Logueo de los usarios al sistema
	 *
	 * @return void
	 */
	public function login(){
		
		$this->layout = 'login';

		//Comprobamos si existe error en el logueo, si es así debemos saber donde devolver el mensaje
		if ($this->Session->check('Message.auth')){

			$routing_prefixes = Configure::read('Routing.prefixes');
			//Si la URL de referencia es diferente a /admin es que esta intentando loguearse desde 
			//la página principal y por tanto devolvemos los errores a la página de donde veniamos
			if(!preg_match('/'.$routing_prefixes[0].'/i', $this->referer())){
				$this->redirect($this->referer());
			}
		}

		#Vista a renderizar
		$this->viewPath = 'elements'.DS.'login';
		$this->render('login');

	}

	/**
	 * DesLogueo de los usarios del sistema
	 *
	 * @return void
	 */
	public function logout(){//Deslogueo de Usuarios
        $this->Session->setFlash('Logout');
	    $this->redirect($this->Auth->logout());
    }

	/**
	 * Encargada de enviar al correo del usuario un nuevo password cuando, este es perdido
	 *
	 * @return void
	 */
	public function recover_pass(){

		$this->autoRender = false;

		if(!empty($this->data)){
		
			//Aseguro la entrada de datos con sanitize
			$this->data = Sanitize::clean($this->data,
										  array('odd_spaces' => true,
												'encode' => false,
												'dollar' => true,
												'carriage' => true,
												'unicode' => true,
												'escape' => false,
												'backslash' => true));

			//Validamos la entrada de datos
			if ($this->User->validates()){
			
				//Compruebo si el email existe o no			
				$data_register = $this->User->FindByEmail($this->data['User']['email']);
				if(empty($data_register)){
					$this->msg_result = "email_no_valid";
					$this->Session->setFlash(__($this->msg_result, true), 'default');
				}else{

					//Obtenemos el nuevo password
					$new_password = $this->Passtrong->MakePassword();
				
					###ENVIAMOS EMAIL DE NOTIFICACION
					//Texto del email
					$text_mail = null;
					$text_mail .= "<h3>".__('recover_password', true)."</h3>";						
					$text_mail .= "<p>";
					$text_mail .= "<strong>".__('user_name', true).":</strong> ".$data_register['User']['username']."<br />";
					$text_mail .= "<strong>".__('user_password', true).":</strong> ".$new_password."<br />";
					$text_mail .= "</p>";
					
					//Enviamos el email
					if($this->sendMail(array('to_mail' => $this->data['User']['email'], 'subject_mail' => __('recover_password', true), 'text_mail' => $text_mail))){
						//Modificamos el password en la BD, solo si se envia el correo.
						$this->User->id = $data_register['User']['id'];
						if(!$this->User->saveField('password', $this->Auth->password($new_password))){
							$this->msg_result = "error_saving";
							$this->Session->setFlash(__($this->msg_result, true), 'default');
						}
					}

				}
					
			}else{
				$this->msg_result = array_shift($this->validateErrors($this->User));
				$this->Session->setFlash(__($this->msg_result, true), 'default');	
			}
			
		}else{
			$this->msg_result = "form_must_fill";
			$this->Session->setFlash(__($this->msg_result, true), 'default');
		}

		$this->redirect($this->referer());
	}



////////////////////////////////////////////////////////////////////////////
//////*ESTOS METODOS DEBEN ESTAR LIMITADOS A LOS ADMINISTRADORES*//////////
//////////////////////////////////////////////////////////////////////////


	/**
	 * Listado de usuarios en el panel de administración
	 *
	 * @return void
	 */
	public function admin_index(){

 		$this->layout = 'admin';

		//numero de registros a mostrar
		if(isset($this->params['named']['nreg']) && in_array($this->params['named']['nreg'],$this->lnregpp)){
			$i_array = array_keys($this->lnregpp,$this->params['named']['nreg']);
			$nreg = $this->lnregpp[$i_array[0]];
		}else{
			$nreg = $this->lnregpp[0];
		}
		
		//palabra a buscar
		(isset($this->params['named']['search'])) ? $search = $this->params['named']['search'] : $search = null;
		//pagina
		(isset($this->params['named']['page'])) ? $page = $this->params['named']['page'] : $page = 1;

		//Parametros que paso al paginador
		$this->paginate = array('limit' => $nreg,
								'order' => null,
								'conditions' => $this->cmp_search." LIKE '%".$search."%'",
								'recursive' => 2);

		//obtengo todos los registros y setemos
		$this->set('registers', $this->paginate('User'));
		
		//menu derecho
		$this->set('action_menu', $this->action_menu);

		//submenu
		$this->set('sub_menu', $this->sub_menu);

		//Mostramos el buscador
		$this->set('search_form', $this->search_form);	

		//palabra buscada
		$this->set('search', $search);

		//lista de valores para mostrar por pantalla
		$this->set('lnregpp', $this->lnregpp);

		//pagina donde me encuentro
		$this->set('page', $page);

		//Valor elegido en la lista de valores
		$this->set('nreg', $nreg);

	}

	/**
	 * Muestra registro pertinente
	 *
	 * @param integer $id indica el identificador del registro a mostrar
	 * @return void
	 */
	public function admin_view($id = null){

 		$this->layout = 'admin';

		//Datos de los grupos
		$this->set('groups', $this->Group->find('all',array($conditions = null, $fields = null, $order = null, $limit = null, $User = null, $recursive = -1 )));

		//Seteo las secciones del menu izquierdo
		$this->set('action_menu', $this->action_menu);

		//Seteo las secciones del submenu
		$this->set('sub_menu', $this->sub_menu);

		//Mostramos el buscador
		$this->set('search_form', $this->search_form);	

		//Datos del registro
		$this->User->id = $id;
        $this->set('register', $this->User->read());
	}



	/**
	 * Añade o actualiza los registros de la BD
	 *
	 * @return void
	 */
	public function admin_add() {

 		$this->autoRender = false;
		
		//para verificar password
		$match_password = true;

		if(!empty($this->data) && $this->RequestHandler->isAjax()){
		//Se ha rellenado el formulario y viene via AJAX
			if((!empty($this->data['User']['id']) && $this->params['form']['change_password'] == '1' && isset($this->params['form']['change_password'])) || (empty($this->data['User']['id']))){
			//Se quieren cambiar las contraseñas
				if($this->data['User']['password'] != $this->Auth->password($this->data['User']['repassword']) || empty($this->data['User']['repassword'])){
				//Contraseñas no coinciden
					$this->result_action = false;
					$this->msg_result = "password_no_match";

					$match_password = false;
				}
			}else{
			//Elimino las variables de las contraseñas
			unset($this->params['form']['change_password']);	
			unset($this->data['User']['password']);	
			unset($this->data['User']['repassword']);			
			}
				
			if($match_password){
			//Si todo va bien

				//Created
				if(empty($this->data['User']['id']))
					$this->data['User']['created'] = date("Y-m-d H:i:s"); 

				//Modified
				if(!empty($this->data['User']['id']))
					$this->data['User']['modified'] = date("Y-m-d H:i:s"); 
		
				//Aseguro la entrada de datos con sanitize
				$this->data = Sanitize::clean($this->data,
											  array('odd_spaces' => true,
													'encode' => false,
													'dollar' => true,
													'carriage' => true,
													'unicode' => true,
													'escape' => false,
													'backslash' => true));

				if ($this->User->create($this->data) && $this->User->validates() && $this->_checkUsersProtected(array("id" =>$this->data['User']['id']))){
				//Todos los datos son correctos

					//Comprobamos si se ha cambiado el grupo del usuario
					$this->_changeGroup($this->data['User']);

					if ($this->User->save($this->data)){
						//Se salvo correctamente

						####INICIO LOG del sistema
						if(isset($this->data['User']['id']) && !empty($this->data['User']['id'])){
							$id_reg = $this->data['User']['id'];
							$action_reg = __("update_user", true);
						}else{
							$id_reg = $this->User->lastReg();
							$action_reg = __("add_user", true);
						}

						$data_log = array ( "title" => "'".$this->data['User']['username']."' (".$action_reg.")",
											"section" => $this->name,
											"url" => Router::url(array('admin' => true,'controller'=> strtolower($this->name), 'action'=>'view', $id_reg), true),
											"created" => date("Y-m-d H:i:s")
											);

						$this->Log->addRegister($data_log);
						####FIN LOG

						//Mensaje a lanzar
						$this->result_action = true;
						$this->msg_result = "data_saved_correctly";
						

					}else{
						//No se salvaron correctamente
						$this->result_action = false;
						$this->msg_result = "error_saving";
					}
				
				}else{
				//Los datos no son correctos o falta alguno requerido
					$this->result_action = false;
					if(empty($this->msg_result))
						$this->msg_result = array_shift($this->validateErrors($this->User));
				}
			
			}

		}else{
		//No se ha rellenado el formulario y no viene via AJAX
			$this->result_action = false;
			$this->msg_result = "form_must_fill";
		}

		//Para cuando se redirija mediante javascript siga mostrando el mensaje
		$url_redirect = Router::url(array('admin' => true,'action'=>'index'), true)."#result_system";
		$this->Session->setFlash(__($this->msg_result, true), 'default');

		//Devuelvo datos del mensaje e identificador (array --> json)
		echo (json_encode(array("result_action" => $this->result_action,
								"msg_result" => __($this->msg_result, true),
								"url_redirect" => $url_redirect
								)
						)
			);

	}

	/**
	 * Elimina registros de la BD
	 *
	 * @return void
	 */
	public function admin_delete(){

		if(isset($this->params['form']['list_reg'])){

			if(count($this->params['form']['list_reg']) != 0){

				for($i = 0; $i < count($this->params['form']['list_reg']); $i++){

					if($this->params['form']['list_reg'][$i] != ""){

						if($this->_checkUsersProtected(array("id" => $this->params['form']['list_reg'][$i]))){

							####INICIO LOG del sistema
							$this->User->id = $this->params['form']['list_reg'][$i];
							$data_register = $this->User->read();

							//datos que se almacenarán en el LOG del sistema y la actividad de session del usuario
							$data_log = array ( "title" => "'".$data_register['User']['username']."' (".__('deleted', true).")",
												"section" => $this->name,
												"url" => null,
												"created" => date("Y-m-d H:i:s")
												);

							$this->Log->addRegister($data_log);
							####FIN LOG

							///borramos usuario
							$this->User->delete($this->params['form']['list_reg'][$i]);

							//datos a devolver
							$this->msg_result = "del_registers_correctly";
						}

					}else{
						//datos a devolver
						$this->msg_result = "error_process_delete";
					}
				}

			}else{
				//datos a devolver
				$this->msg_result = "select_one_register";
			}
				
		}else{
			//datos a devolver
			$this->msg_result = "no_operations";
		}

		//Mensaje que devuelve
		$this->Session->setFlash(__($this->msg_result, true), 'default');
		//Redireccion 
		$this->redirect($this->referer()."#result_system");
	}	


	/**
	 * Cambia el estado del usuario, de activo a inactivo
	 *
	 * @return void
	 */
 	public function admin_setActive(){
 	
 		$this->autoRender = false;
 		 
 		if($this->RequestHandler->isAjax()){

			if($this->_checkUsersProtected(array("id" => $this->params['form']['id'])))
	 			$this->User->setActive($this->params['form']['id'],$this->params['form']['active']);

			####INICIO LOG del sistema
			if($this->params['form']['active'] == '0' || $this->params['form']['active'] == null){
				$state_user = "disabled";
			}else{
				$state_user = "enabled";
			}

			$this->User->id = $this->params['form']['id'];
			$data_register = $this->User->read();

			$data_log = array ( "title" => "user '".$data_register['User']['username']."' ".__($state_user, true),
								"section" => $this->name,
								"url" => Router::url(array('admin' => true,'controller'=> strtolower($this->name), 'action'=>'view', $id_reg), true),
								"created" => date("Y-m-d H:i:s")
								);

			$this->Log->addRegister($data_log);
			####FIN LOG


 		}else{
			//Redireccion
			$this->redirect($this->referer());
 		}
 	}

	
	/**
	 * Muestra los permisos que el usuario tiene habilitados en la BD
	 * 
	 * @return void
	 */
	public function admin_permissions($id){

		if(empty($id)){
			$this->redirect($this->referer());
		}else{

			//Menu nuevo
			$this->action_menu['manager_permissions'] = "permissions";

			//Seteo las secciones del menu izquierdo
			$this->set('action_menu', $this->action_menu);

			//Seteo las secciones del submenu
			$this->set('sub_menu', $this->sub_menu);

			//Mostramos el buscador
			$this->set('search_form', $this->search_form);	

			//Datos del registro
			$this->User->id = $id;
			$data_register = $this->User->read();
	        $this->set('register', $data_register);

			//Padre del arbol general de permisos(controllers => id = 1)
			$this->Aco->id = '1';
	        $data_root = $this->Aco->read();
			$this->set('data_root',$data_root);

			//Todas las acciones posibles listadas
			$registers_permissions = $this->Aco->find('all', array('fields' => array('id','alias','parent_id'), 'conditions' => 'parent_id IS NOT NULL AND lft >= "'.$data_root['Aco']['lft'].'" AND rght <= "'.$data_root['Aco']['rght'].'"','order' => 'lft ASC', "recursive" => "-1"));
			$this->set('registers_permissions', $registers_permissions);


			//Obtengo los valores del ARO del usuario
			$data_aro_user = $this->Aro->find('first', array('conditions' => 'foreign_key = "'.$data_register['User']['id'].'" AND model = "User"', "recursive" => "-1"));

			//Los permisos o privilegios que posee dicho usuario (marcados)
			$active_permissions_user = $this->Permission->find('all', array('conditions' => 'aro_id= "'.$data_aro_user['Aro']['id'].'"', "recursive" => "-1"));

			//Obtengo los valores del ARO del grupo
			$data_aro_group = $this->Aro->find('first', array('conditions' => 'foreign_key = "'.$data_register['User']['group_id'].'" AND model = "Group"', "recursive" => "-1"));

			//Los permisos o privilegios que posee dicho grupo del usuario (marcados), estos no pueden ser editados desde los permisos de usuario
			$active_permissions_group = $this->Permission->find('all', array('conditions' => 'aro_id= "'.$data_aro_group['Aro']['id'].'"', "recursive" => "-1"));
		
			//Averiguo que checkbox deben ser marcados, permisos del grupo, seran desactivados por defecto
			foreach($registers_permissions as $register_permission){

				foreach($active_permissions_group as $active_permission){

					if($register_permission['Aco']['parent_id'] == $active_permission['Permission']['aco_id'] || $register_permission['Aco']['id'] == $active_permission['Permission']['aco_id']){//Su padre
						$active_permissions_view[$active_permission['Permission']['aco_id']]['id'] = $active_permission['Permission']['aco_id'];
						$active_permissions_view[$active_permission['Permission']['aco_id']]['_read'] = $active_permission['Permission']['_read'];
						$active_permissions_view[$active_permission['Permission']['aco_id']]['disabled'] = true;
					}

				}
			}


			//Si se han otorgado permisos al usuario
			if(count($active_permissions_user)>0){
				//Averiguo que checkbox deben ser marcados, permisos del usuario
				foreach($registers_permissions as $register_permission){

					foreach($active_permissions_user as $active_permission){

						if($register_permission['Aco']['parent_id'] == $active_permission['Permission']['aco_id'] || $register_permission['Aco']['id'] == $active_permission['Permission']['aco_id']){//Su padre
							$active_permissions_view[$active_permission['Permission']['aco_id']]['id'] = $active_permission['Permission']['aco_id'];
							$active_permissions_view[$active_permission['Permission']['aco_id']]['_read'] = $active_permission['Permission']['_read'];
						}
					}
				}
			}


			//Indica que checkbox deben estar marcados
			$this->set('active_permissions_view',  $active_permissions_view);

		}

	}	


	/**
	 * Cambia los permisos del usuario en la BD
	 * 
	 * @return void
	 */
	public function admin_changePermissions(){
		
 		$this->autoRender = false;
		
		if(!empty($this->params['form']) && !empty($this->data)){
			//Usuario al que afecta el cambio
			$this->User->id = $this->data['User']['id'];
			$data_register = $this->User->read();
			unset($this->data['User']);

			//Obtengo los valores del ARO del usuario
			$data_aro_user = $this->Aro->find('first', array('conditions' => 'foreign_key = "'.$data_register['User']['id'].'" AND model = "User"', "recursive" => "-1"));

			//Los permisos o privilegios que posee dicho usuario (marcados)
			$bd_active_permissions_user = $this->Permission->find('all', array('conditions' => 'aro_id= "'.$data_aro_user['Aro']['id'].'"', "recursive" => "-1"));

			//Obtengo los valores del ARO del grupo
			$data_aro_group = $this->Aro->find('first', array('conditions' => 'foreign_key = "'.$data_register['User']['group_id'].'" AND model = "Group"', "recursive" => "-1"));

			//Los permisos o privilegios que posee dicho grupo del usuario (marcados), estos no pueden ser editados desde los permisos de usuario
			$bd_active_permissions_group = $this->Permission->find('all', array('conditions' => 'aro_id= "'.$data_aro_group['Aro']['id'].'"', "recursive" => "-1"));

			//Los nuevos asignados por el usuario
			$user_active_permissions = $this->_prepare_permissions($this->params['form']);

			//Se actualizan o se borran permisos del usuario, no del grupo
			foreach($bd_active_permissions_user as $bd_permission){

				if(isset($user_active_permissions[$bd_permission['Permission']['aco_id']])){//Actualizamos

					//Preparamos los datos
					$this->data['Permission']['id'] = $bd_permission['Permission']['id'];
					$this->data['Permission']['aro_id'] = $bd_permission['Permission']['aro_id'];
					$this->data['Permission']['aco_id'] = $bd_permission['Permission']['aco_id'];
					if(isset($user_active_permissions[$bd_permission['Permission']['aco_id']]['_read']) && $user_active_permissions[$bd_permission['Permission']['aco_id']]['_read'] == 1){
						$this->data['Permission']['_read'] = 1;
						$this->data['Permission']['_create'] = 1;
						$this->data['Permission']['_update'] = 1;
						$this->data['Permission']['_delete'] = 1;
					}else{
						$this->data['Permission']['_read'] = 0;
						$this->data['Permission']['_create'] = 0;
						$this->data['Permission']['_update'] = 0;
						$this->data['Permission']['_delete'] = 0;
					}

					//Salvamos
					$this->Permission->save($this->data);
					//Lo eliminamos del array nuevo, los que sobren, seran de nueva inserccion
					unset($user_active_permissions[$bd_permission['Permission']['aco_id']]);

				}else{//Eliminamos
					$this->Permission->delete($bd_permission['Permission']['id']);
				}
				
			}


			//Antes de nada he de quitar los permisos que el mismo grupo otorga al usuario
			//Ya que aqui solo tratamos los permisos del usuario, los del grupo ya tiene su propia seccion
			foreach($bd_active_permissions_group as $bd_permission){
				if(isset($user_active_permissions[$bd_permission['Permission']['aco_id']]))//Borramos dicha entrada
					unset($user_active_permissions[$bd_permission['Permission']['aco_id']]);
			}

			//Inserccion de nuevos permisos
			if(count($user_active_permissions) > 0){
				foreach ($user_active_permissions as $user_permission){

					//Preparamos los datos
					$this->data['Permission']['id'] = null;
					$this->data['Permission']['aro_id'] = $data_aro_user['Aro']['id'];
					$this->data['Permission']['aco_id'] = $user_permission['aco_id'];

					if(isset($user_permission['_read']) && $user_permission['_read'] == 1){
						$this->data['Permission']['_read'] = 1;
						$this->data['Permission']['_create'] = 1;
						$this->data['Permission']['_update'] = 1;
						$this->data['Permission']['_delete'] = 1;
					}else{
						$this->data['Permission']['_read'] = 0;
						$this->data['Permission']['_create'] = 0;
						$this->data['Permission']['_update'] = 0;
						$this->data['Permission']['_delete'] = 0;
					}
				
					//Salvamos
					$this->Permission->save($this->data);
				}
			}

			####INICIO LOG del sistema
			$data_log = array ( "title" => __('update_permissions_user', true)." '".$data_register['User']['username']."'",
								"section" => $this->name,
								"url" => Router::url(array('admin' => true,'controller'=> strtolower($this->name), 'action'=>'permissions', $data_register['User']['id']), true),
								"created" => date("Y-m-d H:i:s")
								);

			$this->Log->addRegister($data_log);
			####FIN LOG

			//Mensaje a lanzar
			$this->msg_result = "data_saved_correctly";

		}else{
			$this->msg_result = "form_must_fill";
		}			

		//Mensaje que devuelve
		$this->Session->setFlash(__($this->msg_result, true), 'default');
		//Redireccion 
		$this->redirect($this->referer());

	}	


	/**
	 * Comprueba la fuerza del password que el usuario inserto
	 * 
	 * @return void
	 */
	public function admin_getPassStrength(){
		
		$this->autoRender = false;
		
		if($this->RequestHandler->isAjax()){
				$result_pass = $this->Passtrong->CheckPasswordStrength($this->params['form']['password']);
				//Devuelvo Json
				echo (json_encode($result_pass));
		}
	}


	/**
	 * Prepara los permisos que llegan del formulario para poder ser tratados en la función admin_changePermissions
	 *
	 * @param array $new_permissions de los checkbox marcados en el formulario
	 * @return array
	 */
	private function _prepare_permissions($new_permissions){

		//Por cada elemento enviado del formulario
		foreach ($new_permissions as $key => $value){
		
			$parts_key = explode("_", $key);

			//Aseguro que la entrada sea la correcta de datos
			if($parts_key[0] == 'reg' && is_numeric($parts_key[1])){

				$new_permissions_corrected[$parts_key[1]]['aco_id'] = $parts_key[1];
				$new_permissions_corrected[$parts_key[1]]['_read'] = $value;
				$new_permissions_corrected[$parts_key[1]]['_create'] = $value;
				$new_permissions_corrected[$parts_key[1]]['_update'] = $value;
				$new_permissions_corrected[$parts_key[1]]['_delete'] = $value;

			}

		}
		return $new_permissions_corrected;
	}
	/**
	 * Encargada de cambiar de ARO al usuario si este cambia de grupo
	 * si lo hacen desde la BD eso ya no podré impedirlo
	 *
	 * @param array user datos del usuario a tratar
	 * @return void
	 */
	private function _changeGroup($user){

		if(!empty($user['id'])){
			$this->User->id = $user['id'];
			$oldgroupid = $this->User->field('group_id');
			if ($oldgroupid !== $user['group_id']) {
				$aro =& $this->Acl->Aro;
				$user = $aro->findByForeignKeyAndModel($user['id'], 'User');
				$group = $aro->findByForeignKeyAndModel($user['group_id'], 'Group');
					
				// Guardar en la tabla ARO
				$aro->id = $user['Aro']['id'];
				$aro->save(array('parent_id' => $group['Aro']['id']));
			}
		}

	}


	/**
	 * Función que impide que borremos o modifiquemos accidentalmente usuarios protegidos
	 * si lo hacen desde la BD eso ya no podré impedirlo
	 *
	 * @param array options para identificar al usuario a borrar
	 * @return bool
	 */
	private function _checkUsersProtected($options, $users = null){

		if(!empty($users) && is_array($users))
			$this->_users_protected = $users; //<-- lista de usuario que no pueden ser borrados

		//Recorro cada uno de los usuarios del array
		foreach ($this->_users_protected as $user){
			if($options['id'] == $user['id'] || $options['username'] == $user['username']){
				$this->result_action = false;
				$this->msg_result = 'users_protected';
				return false;
			}
		}

		return true;
	}

	
}

?>
